import { Notification } from '@alifd/next';
import { t } from '@lingui/macro';

/**
 * 计算分账方金额汇总
 * @param {*} initAccount 初始化数组
 * @param {*} accountsTotal 已改变数组
 * @param {*} setAccountTotal 方法函数
 */
export const calculateTotal = (initAccount, accountsTotal, setAccountTotal) => {
  // 复制 accounts 数组以防止修改原始数据
  const updatedAccounts = initAccount.map((accountItem) => ({ ...accountItem }));
  // 计算总和并更新 updatedAccounts 数组
  for (const item of accountsTotal) {
    if (item.account) {
      const bArray = item.account;
      for (const obj of bArray) {
        const { targetName, contributionAmount, pendingSettlementAmount } = obj;
        // 在 updatedAccounts 数组中找到匹配项并更新
        const matchedIndex = updatedAccounts.findIndex((accountItem) => accountItem.targetName === targetName);
        if (matchedIndex !== -1) {
          updatedAccounts[matchedIndex].pendingSettlementAmount += parseFloat(pendingSettlementAmount) || 0;
          updatedAccounts[matchedIndex].contributionAmount += parseFloat(contributionAmount) || 0;
        }
      }
    }
  }
  // 输出更新后的结果
  setAccountTotal([...updatedAccounts]);
};


/**
 * 校验每张车票金额输入金额是否超过可退金额
 * @param {*} ticketRefund 后端返回已退车票金额
 * @param {*} orderDetails 全部车票
 * @param {*} v 输入的金额
 * @param {*} r 当前车票信息
 * @returns true or false
 */
export const verifyTicketPrice = (ticketRefund, orderDetails, v, r) => {
  let currentNext;
  if (JSON.stringify(ticketRefund) !== '{}') {
    // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
    Object.entries(ticketRefund).forEach(([key, value]) => {
      const findTicket = orderDetails?.find((item) => item.operatingTicketCode === key);
      if (findTicket) {
        const { ticketPrice } = findTicket;
        if ((Number(ticketPrice) - Number(value)) < Number(v)) {
          currentNext = true;
          return Notification.open({
            title: '警告⚠️',
            content:
              t`当前车票可退金额为: ${(Number(ticketPrice) - Number(value)).toFixed(2)}`,
            type: 'warning',
          });
        } else {
          currentNext = false;
        }
      } else if ((Number(r.price) - Number(v)) < 0) {
        currentNext = true;
        return Notification.open({
          title: '警告⚠️',
          content:
            t`当前车票可退金额为: ${Number(r.price).toFixed(2)}`,
          type: 'warning',
        });
      } else {
        currentNext = false;
      }
    });
  } else if ((Number(r.ticketPrice) - Number(v)) < 0) {
    currentNext = true;
    return Notification.open({
      title: '警告⚠️',
      content:
        t`当前车票可退金额为: ${Number(r.ticketPrice).toFixed(2)}`,
      type: 'warning',
    });
  } else {
    currentNext = false;
  }
  return currentNext;
};

/**
 * 二次校验退款金额和分账方金额
 * @param {*} orderRefundStatus 当前页面
 * @param {*} accountTotal 分账方汇总
 * @param {*} initOtherAccounts 其他退款的分账信息
 * @param {*} orderRefund 当前订单信息
 * @returns true
 */
export const verifyAccount = (orderRefundStatus, accountTotal, initOtherAccounts, orderRefund) => {
  let targetAccounts;
  if (orderRefundStatus === '0') {
    targetAccounts = accountTotal;
  } else if (orderRefundStatus === '1') {
    targetAccounts = initOtherAccounts;
  }
  // 校验分账方出资金额不可大于待分账金额
  const isValid = targetAccounts.every((account) => {
    const contributionAmount = Number(account.contributionAmount);
    const pendingSettlementAmount = Number(account.pendingSettlementAmount);
    return contributionAmount <= pendingSettlementAmount;
  });
  if (!isValid) {
    // 如果有任何一条数据不符合条件，进行相应的处理
    return Notification.open({
      title: '警告⚠️',
      content: '分账方的出资金额不可大于分账金额!',
      type: 'warning',
    });
  }
  // 第一次取消校验  https://pm.aspiretop.com/issues/3365
  // 第二次更改校验  校验退款金额和分账方金额汇总相同
  if (accountTotal) {
    const sum = targetAccounts.reduce((accumulator, currentValue) => accumulator + parseFloat(currentValue.contributionAmount), 0);
    console.log('专线verifyAccount校验___埋点:', toJS(orderRefund.refundPrice), sum);
    if (Number(orderRefund.refundPrice) > sum) {
      return Notification.open({
        title: '警告⚠️',
        content: '分账方金额必须高于或等于退款金额!',
        type: 'warning',
      });
    }
  }
};

/**
 * 计算两个数组是否一样
 * @param {*} arr1
 * @param {*} arr2
 * @returns true
 */
export const areArraysEqual = (arr1, arr2) => {
  return JSON.stringify(arr1) === JSON.stringify(arr2);
};

/**
 * 是否可以编辑分账方待分账金额
 * @param {*} enableProfitShare
 * @returns
 */
export const currentEditAccount = (enableProfitShare) => {
  if (enableProfitShare) {
    Notification.open({
      title: '警告⚠️',
      content: '已开启分账不可编辑分账方待分账金额!',
      type: 'warning',
    });
    return true;
  } else {
    return false;
  }
};

/**
 * 还原数组 contributionAmount 金额, 由于页面上展示需要做处理 但是后端需要原数据
 * @param {*} arr1
 * @param {*} arr2
 */
export const arrayContrast = (open, arr1, arr2) => {
  if (open) {
    const account = arr2.map((item) => ({
      ...item,
      pendingSettlementAmount: Number(item.pendingSettlementAmount) * 100,
      contributionAmount: Number(item.contributionAmount) * 100,
    }));
    return account;
  } else {
    const compute = arr1?.map((item) => {
      const findIdx = arr2?.find((p) => p.targetName === item.targetName);
      if (findIdx) {
        // eslint-disable-next-line no-param-reassign
        item.pendingSettlementAmount = Number(findIdx.pendingSettlementAmount) * 100;
        item.contributionAmount = Number((Number(item.contributionAmount) * 100).toFixed(0));
      }
      return item;
    });
    return compute;
  }
};

/**
 * 计算分账方金额修改后总额必须和修改之前相同
 * @param {*} arr1
 * @param {*} arr2
 */
export const verifyAccountTotal = (arr1, arr2) => {
  const compute = arr1?.map((item) => ({
    ...item,
    pendingSettlementAmount: item.pendingSettlementAmount - item.refundedAmount,
  }));
  const sum1 = compute.reduce((accumulator, currentValue) => accumulator + JSON.parse(currentValue.pendingSettlementAmount), 0);
  const sum2 = arr2.reduce((accumulator, currentValue) => accumulator + JSON.parse(currentValue.pendingSettlementAmount) * 100, 0);
  if (JSON.parse(sum1.toFixed(2)) === JSON.parse(sum2.toFixed(2))) {
    return false;
  } else {
    Notification.open({
      title: '警告⚠️',
      content: t`修改后分账方待分账金额总和需和修改前的分账方金额总和相等, 修改前待分账总和为 ${(sum1 / 100).toFixed(2)} 元!`,
      type: 'warning',
    });
    return true;
  }
};

/**
 * 退款提示 追加退款金额不能为0
 */
export const refundCaution = () => {
  return Notification.open({
    title: '警告⚠️',
    content: t`退款金额不能为0!`,
    type: 'warning',
  });
};

/**
 * 计算分账方出资金额是否为0
 * @param {*} arr1
 * @param {*} arr2
 * @returns true
 */
export const currentIsEdit = (arr1) => {
  const sum = arr1.reduce((accumulator, currentValue) => accumulator + Number(currentValue.contributionAmount), 0);
  if (sum === 0) {
    return false;
  } else {
    Notification.open({
      title: '警告⚠️',
      content: '已修改退款出资金额就不能修改待分账金额!',
      type: 'warning',
    });
    return true;
  }
};
/**
 * 计算是否可以编辑分账方出资金额
 * @param {*} arr1 初始分账方
 * @param {*} arr2 修改后的分账方
 */
export const currentIsEditPS = (arr1, arr2) => {
  const initSum = arr1.reduce((accumulator, currentValue) => accumulator + Number(currentValue.pendingSettlementAmount) * 100, 0);
  const sum = arr2.reduce((accumulator, currentValue) => accumulator + Number(currentValue.pendingSettlementAmount) * 100, 0);
  if (Number(initSum.toFixed(0)) === Number(sum.toFixed(0))) {
    return false;
  } else {
    Notification.open({
      title: '警告⚠️',
      content: '已编辑待分账金额就不能编辑出资金额!',
      type: 'warning',
    });
    return true;
  }
};

/**
 * 计算确定退款金额
 */
export function computePrice(data) {
  const perices = {
    platformPrice: null,
    otherPrice: null,
  };
  const { discountInfos = [] } = data?.order;
  const { refundPrice } = data;
  const costTotal = discountInfos.filter((p) => p.source !== 'WX').reduce((acc, item) => {
    const { cost } = item;
    acc += cost;
    return acc;
  }, 0);
  // 第二种  只存在第三方退款
  if (costTotal >= refundPrice) {
    perices.otherPrice = refundPrice;
  }
  // 第三种  都存在
  if (costTotal < refundPrice) {
    perices.otherPrice = costTotal;
    perices.platformPrice = refundPrice - costTotal;
  }
  // 第一种  不存在优惠金额
  if (discountInfos.length === 0) {
    perices.platformPrice = refundPrice;
    perices.otherPrice = null;
  }
  return perices;
}
